package com.kaizeli.website.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kaizeli.website.mapper.ProjectBasicInfoMapper;
import com.kaizeli.website.pojo.dto.base.PageDTO;
import com.kaizeli.website.pojo.entity.ProjectBasicInfoDO;
import com.kaizeli.website.pojo.vo.ProjectBasicInfoVO;
import com.kaizeli.website.query.ProjectBasicInfoQuery;
import com.kaizeli.website.service.ProjectBasicInfoService;
import com.kaizeli.website.mapper.ProjectAcceptanceMapper;
import com.kaizeli.website.mapper.AcceptanceMemberMapper;
import com.kaizeli.website.pojo.entity.ProjectAcceptance;
import com.kaizeli.website.pojo.entity.AcceptanceMember;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目基础信息服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProjectBasicInfoServiceImpl implements ProjectBasicInfoService {
    
    private final ProjectBasicInfoMapper projectBasicInfoMapper;
    private final ProjectAcceptanceMapper projectAcceptanceMapper;
    private final AcceptanceMemberMapper acceptanceMemberMapper;
    
    @Override
    public PageDTO<ProjectBasicInfoVO> pageQuery(ProjectBasicInfoQuery query) {
        Page<ProjectBasicInfoDO> page = new Page<>(query.getPageNum(), query.getPageSize());
        
        QueryWrapper<ProjectBasicInfoDO> queryWrapper = new QueryWrapper<>();
        if (query.getProjectCode() != null && !query.getProjectCode().isEmpty()) {
            queryWrapper.like("project_code", query.getProjectCode());
        }
        if (query.getProjectName() != null && !query.getProjectName().isEmpty()) {
            queryWrapper.like("project_name", query.getProjectName());
        }
        if (query.getStatus() != null && !query.getStatus().isEmpty()) {
            queryWrapper.eq("status", query.getStatus());
        }
        if (query.getCustomerId() != null) {
            queryWrapper.eq("customer_id", query.getCustomerId());
        }
        if (query.getContractCompanyId() != null) {
            queryWrapper.eq("contract_company_id", query.getContractCompanyId());
        }
        if (query.getProjectType() != null) {
            queryWrapper.eq("project_type", query.getProjectType());
        }
        if (query.getStartDateBegin() != null) {
            queryWrapper.ge("start_date", query.getStartDateBegin());
        }
        if (query.getStartDateEnd() != null) {
            queryWrapper.le("start_date", query.getStartDateEnd());
        }
        queryWrapper.orderByDesc("id");
        
        Page<ProjectBasicInfoDO> result = projectBasicInfoMapper.selectPage(page, queryWrapper);
        return PageDTO.of(result, this::convertToVO);
    }
    
    @Override
    public ProjectBasicInfoVO getById(Long id) {
        ProjectBasicInfoDO projectDO = projectBasicInfoMapper.selectById(id);
        if (projectDO == null) {
            return null;
        }
        return convertToVO(projectDO);
    }
    
    @Override
    public ProjectBasicInfoVO getByProjectCode(String projectCode) {
        QueryWrapper<ProjectBasicInfoDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_code", projectCode);
        ProjectBasicInfoDO projectDO = projectBasicInfoMapper.selectOne(queryWrapper);
        if (projectDO == null) {
            return null;
        }
        return convertToVO(projectDO);
    }
    
    @Override
    public Long save(ProjectBasicInfoDO projectBasicInfoDO) {
        try {
            LocalDateTime now = LocalDateTime.now();
            projectBasicInfoDO.setCreatedAt(now);
            projectBasicInfoDO.setUpdatedAt(now);
            // 设置创建人ID，如果为空则设置为1（系统用户）
            if (projectBasicInfoDO.getCreatedBy() == null) {
                projectBasicInfoDO.setCreatedBy(1L);
            }
            
            // 生成项目编号，如果为空
            if (projectBasicInfoDO.getProjectCode() == null || projectBasicInfoDO.getProjectCode().trim().isEmpty()) {
                String projectCode = generateProjectCode();
                projectBasicInfoDO.setProjectCode(projectCode);
                log.info("自动生成项目编号：{}", projectCode);
            }
            
            // 设置预计成本默认值，如果为空则设置为0
            if (projectBasicInfoDO.getEstimatedCost() == null) {
                projectBasicInfoDO.setEstimatedCost(BigDecimal.ZERO);
            }
            
            projectBasicInfoMapper.insert(projectBasicInfoDO);
            return projectBasicInfoDO.getId();
        } catch (Exception e) {
            log.error("新增项目基础信息失败", e);
            throw e;
        }
    }
    
    /**
     * 生成项目编号
     * 格式：PROJ + 年月日 + 4位随机数
     * 例如：PROJ20250125001
     */
    private String generateProjectCode() {
        LocalDate now = LocalDate.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        
        // 查询当天已生成的项目编号数量
        QueryWrapper<ProjectBasicInfoDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("project_code", "PROJ" + dateStr);
        long count = projectBasicInfoMapper.selectCount(queryWrapper);
        
        // 生成4位序号，从0001开始
        String sequence = String.format("%04d", count + 1);
        
        return "PROJ" + dateStr + sequence;
    }
    
    @Override
    public Boolean update(ProjectBasicInfoDO projectBasicInfoDO) {
        projectBasicInfoDO.setUpdatedAt(LocalDateTime.now());
        return projectBasicInfoMapper.updateById(projectBasicInfoDO) > 0;
    }
    
    @Override
    public Boolean deleteById(Long id) {
        return projectBasicInfoMapper.deleteById(id) > 0;
    }
    
    @Override
    public List<ProjectBasicInfoVO> listByCustomerId(Long customerId) {
        List<ProjectBasicInfoDO> list = projectBasicInfoMapper.selectList(
            new QueryWrapper<ProjectBasicInfoDO>().eq("customer_id", customerId)
        );
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }
    
    @Override
    public List<ProjectBasicInfoVO> listByContractCompanyId(Long contractCompanyId) {
        List<ProjectBasicInfoDO> list = projectBasicInfoMapper.selectList(
            new QueryWrapper<ProjectBasicInfoDO>().eq("contract_company_id", contractCompanyId)
        );
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }
    
    @Override
    public List<ProjectBasicInfoVO> listByStatus(String status) {
        List<ProjectBasicInfoDO> list = projectBasicInfoMapper.selectList(
            new QueryWrapper<ProjectBasicInfoDO>().eq("status", status)
        );
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }
    
    @Override
    public List<ProjectBasicInfoVO> listAll() {
        try {
            List<ProjectBasicInfoDO> list = projectBasicInfoMapper.selectList(null);
            return list.stream().map(this::convertToVO).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("查询所有项目失败", e);
            throw e;
        }
    }
    
    /**
     * 测试数据库连接
     */
    public List<ProjectBasicInfoDO> testDatabase() {
        try {
            // 直接查询DO对象，不进行转换
            List<ProjectBasicInfoDO> list = projectBasicInfoMapper.selectList(null);
            log.info("数据库测试成功，查询到{}条记录", list.size());
            return list;
        } catch (Exception e) {
            log.error("数据库测试失败", e);
            throw e;
        }
    }
    
    /**
     * 转换为VO
     */
    private ProjectBasicInfoVO convertToVO(ProjectBasicInfoDO projectDO) {
        if (projectDO == null) {
            return null;
        }
        
        ProjectBasicInfoVO vo = new ProjectBasicInfoVO();
        vo.setId(projectDO.getId());
        vo.setProjectCode(projectDO.getProjectCode());
        vo.setProjectName(projectDO.getProjectName());
        vo.setProjectSubname(projectDO.getProjectSubname());
        vo.setStartDate(projectDO.getStartDate());
        vo.setEndDate(projectDO.getEndDate());
        vo.setProjectBudget(projectDO.getProjectBudget());
        vo.setEstimatedCost(projectDO.getEstimatedCost());
        vo.setProjectType(projectDO.getProjectType());
        vo.setProjectTypeName(getProjectTypeName(projectDO.getProjectType()));
        vo.setCustomerId(projectDO.getCustomerId());
        vo.setContractCompanyId(projectDO.getContractCompanyId());
        vo.setManagerId(projectDO.getManagerId());
        vo.setDirectorId(projectDO.getDirectorId());
        vo.setDescription(projectDO.getDescription());
        vo.setStatus(projectDO.getStatus());
        vo.setCreatedAt(projectDO.getCreatedAt());
        vo.setUpdatedAt(projectDO.getUpdatedAt());
        vo.setCreatedBy(projectDO.getCreatedBy());
        return vo;
    }
    
    @Override
    @Transactional
    public Boolean voidProject(Long id) {
        try {
            // 1. 查询项目是否存在
            ProjectBasicInfoDO project = projectBasicInfoMapper.selectById(id);
            if (project == null) {
                log.error("项目不存在，ID: {}", id);
                return false;
            }
            
            // 2. 更新项目状态为"作废审批中"
            project.setStatus("作废审批中");
            project.setUpdatedAt(LocalDateTime.now());
            projectBasicInfoMapper.updateById(project);
            
            // 3. 查询该项目关联的所有验收单
            List<ProjectAcceptance> acceptances = projectAcceptanceMapper.selectList(
                new QueryWrapper<ProjectAcceptance>().eq("project_id", id)
            );
            
            // 4. 遍历验收单，更新验收单状态和验收成员状态
            for (ProjectAcceptance acceptance : acceptances) {
                // 更新验收单状态为"作废审批中"
                acceptance.setStatus("作废审批中");
                acceptance.setUpdateTime(LocalDateTime.now());
                projectAcceptanceMapper.updateById(acceptance);
                
                // 查询该验收单的所有验收成员
                List<AcceptanceMember> members = acceptanceMemberMapper.selectList(
                    new QueryWrapper<AcceptanceMember>().eq("acceptance_id", acceptance.getId())
                );
                
                // 更新所有验收成员的状态为"作废审批中"
                for (AcceptanceMember member : members) {
                    member.setStatus("作废审批中");
                    member.setUpdateTime(LocalDateTime.now());
                    acceptanceMemberMapper.updateById(member);
                }
            }
            
            log.info("项目作废成功，ID: {}, 关联验收单数量: {}, 验收成员数量: {}", 
                id, acceptances.size(), 
                acceptances.stream().mapToInt(a -> acceptanceMemberMapper.selectList(
                    new QueryWrapper<AcceptanceMember>().eq("acceptance_id", a.getId())
                ).size()).sum());
            
            return true;
        } catch (Exception e) {
            log.error("作废项目失败，ID: {}", id, e);
            throw new RuntimeException("作废项目失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据项目类型字符串获取类型名称
     */
    private String getProjectTypeName(String projectType) {
        if (projectType == null || projectType.isEmpty()) {
            return null;
        }
        
        switch (projectType.toLowerCase()) {
            case "manpower":
            case "1":
                return "人力项目";
            case "turnkey":
            case "2":
                return "整包项目";
            case "subcontract":
            case "3":
                return "分包项目";
            default:
                return projectType; // 如果不知道的类型，直接返回原值
        }
    }
}

